package com.cxb.springboot.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @Classname MyHttpServletRequestWrapper
 * @Date 2023/4/15 0:04
 * @Created by Administrator
 * @Description 解决：java.lang.IllegalStateException: getReader() has already been called for this request
 */
@Slf4j
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private byte[] body;

    public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = streamToByte(request.getInputStream());
    }

    /**
     * @param is 输入流
     * @return 将输入流转为字节数组
     */
    public static byte[] streamToByte(InputStream is) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int i;
        try {
            //将输入流中的数据读到bytes中，i表示bytes的长度，当读完时i=-1退出循环
            while ((i = is.read(bytes)) != -1) {
                //将指定的字节数组从偏移量off开始，写入i个字节到输出流
                bos.write(bytes, 0, i);
            }
        } catch (Exception e) {
            log.error("输入流转字节数组失败", e);
        }
        return bos.toByteArray();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return bais.available() == 0;
            }
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            public void setReadListener(ReadListener readListener) {

            }
            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }

    public byte[] getBody() {
        return body;
    }

}

